import { postV3TokenStoreOss } from "@/assets/api";
import { ElMessage } from "element-plus";
import OSS from "ali-oss";

export const initOssApi = (): Promise<ObjValueAny> => {
    return new Promise(resolve => {
        postV3TokenStoreOss({ noRouter: true }).then((resp: ObjValueAny) => {
            if (resp.code === 200) {
                const { data } = resp;
                const ossOption: ObjValueAny = {
                    savePath: data.path,
                    accessKeySecret: data.access_key_secret,
                    stsToken: data.security_token,
                    accessKeyId: data.access_key_id,
                    refreshSTSToken: {
                        accessKeyId: data.access_key_id,
                        accessKeySecret: data.access_key_secret,
                        stsToken: data.security_token,
                    },
                    host: data.host,
                    region: data.region,
                    bucket: data.bucket,
                    refreshSTSTokenInterval: 300000,
                };
                resolve({
                    ossOption,
                    dockOss: new OSS(ossOption),
                });
            } else {
                if (resp.msg) {
                    ElMessage.closeAll();
                    ElMessage.error(resp.msg);
                }
                resolve({});
            }
        })
    })
}


// 上传文件选择类型限制 示例：image/png
export const handlerAccept = (accept: string, type: string) => {
    if (accept) {
        const acceptValue = accept.split(',');
        const acceptMap = acceptValue.map((str: string) => `${type}/${str.trim()}`);
        return acceptMap.join(',');
    } else {
        return `${type}/*`;
    }
}

export const getJudgmentPrompt = (raw: File, accept: string, maxSize: number, prompt: ObjValueStr = {}): string => {
    const sizeStatus = judgmentSizeError(raw, maxSize);
    if (sizeStatus) {
        return prompt.size || '文件过大';
    }
    const extStatus = judgmentExtError(raw, accept);
    if (extStatus) {
        return prompt.accept || '格式错误';
    }
    return '';
}

// 文件格式判断
export const judgmentExtError = (file: File, accept: string, type?: string): string => {
    if (accept) {
        // 获取文件格式
        const _index = file.name.lastIndexOf('.');
        const _fileExt = file.name.substring(_index + 1).toLowerCase();

        const _ext = accept.toLowerCase().replace(/\s+/g, '');
        if (!_ext.includes(_fileExt)) {
            return '格式错误';
        }
    } else {
        const splitType = file.type.split('/');
        return !splitType.includes(type as string) ? '格式错误' : '';
    }
    return '';
}

// 文件大小判断
export const judgmentSizeError = (file: File, max: number): string => {
    const _maxSize = max * 1024 * 1024;// 文件大小限制
    const _size = file.size;// 文件大小
    if (_size > _maxSize) {
        return '格式错误';
    }
    return '';
}